<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <TodoHeader @addName="addName" />
    <!-- 主体部分 -->
    <TodoMain :list="showList" @doDel="doDel" @doChange="doChange" @isAllCheck="isAllCheck" />
    <!-- 底部部分 -->
    <TodoFooter :list="showList" @doClear="doClear" @getType="getType" />
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: { TodoFooter, TodoHeader, TodoMain },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')||'[]'),
      type:'all'
    };
    
  },
  methods:{
    doDel(id){
      const index =this.list.findIndex(item=>item.id===id)
      this.list.splice(index,1)
    },
    doChange(id){
      const obj =this.list.find(item=>item.id===id)
      obj.isDone=!obj.isDone
    },
    addName(name){
      this.list.push({
        name,
        id:Date.now(),
        isDone:false
      })
    },
    doClear(){
      this.list=this.list.filter(item=>!item.isDone)
    },
    getType(type){
      this.type=type
    },
    isAllCheck(val){
      this.list.forEach(item=>item.isDone=val)
    }
  },
  computed:{
    showList(){
      if(this.type==='all'){
        return this.list
      }else if(this.type==='active'){
        return this.list.filter(item=>!item.isDone)
      }else{
        return this.list.filter(item=>item.isDone)
      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler(){
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  }
};
</script>

<style></style>
